package com.phs.main.common;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

import java.io.FileInputStream;
import java.util.Properties;

public class MybatisPlusGenerator {

	public void generator() {
		String dir = "/src/main/java";

		String propPath = "/src/main/resources/application-source.properties";

		String parent = "com.phs.main.web";
		String moduleName = null;
		String entityPackageName = "po";
		String mapperPackageName = "mapper";
		String servicePackageName = "service";
		String serviceImplPackageName = "service.impl";
		String controllerPackageName = "controller";

		String projectPath = System.getProperty("user.dir");
		String root = "spring.datasource.druid.";
		String Url, DriverName, Username, Password;

		try {
			FileInputStream propertiesPath = new FileInputStream(projectPath + propPath);
			Properties prop = new Properties();
			prop.load(propertiesPath);
			propertiesPath.close();

			Url = prop.getProperty(root + "url");
			DriverName = (prop.getProperty(root + "driver-class-name"));
			Username = (prop.getProperty(root + "username"));
			Password = (prop.getProperty(root + "password"));
		} catch (Exception e) {
			e.printStackTrace();
			return;
		}

		// 数据源配置，通过该配置，指定需要生成代码的具体数据库
		DataSourceConfig dataSourceConfig = new DataSourceConfig()
				// 数据库类型, 该类内置了常用的数据库类型
				.setDbType(DbType.MYSQL)
				.setUrl(Url)
				.setDriverName(DriverName)
				.setUsername(Username)
				.setPassword(Password);

		// 全局策略配置
		GlobalConfig globalConfig = new GlobalConfig()
				// 生成文件的输出目录
				.setOutputDir(projectPath + dir)
				// 是否覆盖已有文件
				.setFileOverride(true)
				// 是否打开输出目录
				.setOpen(false)
				.setSwagger2(true)
				.setAuthor("Trent");

		// 包名配置，通过该配置，指定生成代码的包路径
		PackageConfig packageConfig = new PackageConfig()
				// 父包名。如果为空，将下面子包名必须写全部， 否则就只需写子包名
				.setParent(parent)
				.setModuleName(moduleName)
				.setEntity(entityPackageName)
				.setMapper(mapperPackageName)
				.setService(servicePackageName)
				.setServiceImpl(serviceImplPackageName)
				.setController(controllerPackageName);

		// 策略配置
		StrategyConfig strategyConfig = new StrategyConfig()
				// 数据库表映射到实体的命名策略
				.setNaming(NamingStrategy.underline_to_camel)
				.setEntityLombokModel(true)
				// 生成 @RestController 控制器
				.setRestControllerStyle(true);

		// 代码生成器，具体请查看 https://mybatis.plus/config/generator-config.html#template
		new AutoGenerator()
				.setGlobalConfig(globalConfig)
				.setDataSource(dataSourceConfig)
				.setPackageInfo(packageConfig)
				.setStrategy(strategyConfig)
				// 模板配置，可自定义代码生成的模板，实现个性化操作
				.setTemplate(new TemplateConfig().setXml(null))
				.setTemplateEngine(new FreemarkerTemplateEngine())
				.execute();
	}

}
